<!-- #layout name=blank -->
<div id="app">
  <div class="page-header">
    <h1 class="title">Authentication</h1>
  </div>
  <kb-breadcrumb :breads="breads"></kb-breadcrumb>
  <div class="navbar navbar-default">
    <div class="container-fluid">
      <a class="btn green navbar-btn" @click="onCreateOrEdit()">Create</a>
      <a
        class="btn red navbar-btn"
        v-show="selectedRows.length>0"
        @click="onDelete"
        >Delete</a
      >
    </div>
  </div>
  <kb-table :data="model" show-select :selected.sync="selectedRows">
    <kb-table-column :label="Kooboo.text.common.name">
      <template v-slot="row">
        <span @click.stop="">{{ row.name }}</span>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.matcher">
      <template v-slot="row">
        <span @click.stop=""
          >{{ row.matcher=='Condition'?getConditionStr(row):row.matcher }}</span
        >
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.site.siteLog.action">
      <template v-slot="row">
        <span @click.stop="">{{ row.action }}</span>
      </template>
    </kb-table-column>

    <kb-table-column
      :label="Kooboo.text.common.failed+Kooboo.text.site.siteLog.action"
    >
      <template v-slot="row">
        <span @click.stop=""
          >{{row.action=='CustomCode'?'CustomCode': row.failedAction }}</span
        >
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.component.viewEditor.parameter">
      <template v-slot="row">
        <span @click.stop="">{{getParameter(row)}}</span>
      </template>
    </kb-table-column>

    <kb-table-column :label="Kooboo.text.common.lastModified">
      <template v-slot="row">
        <span> {{ new Date(row.lastModified).toDefaultLangString() }} </span>
      </template>
    </kb-table-column>

    <kb-table-column align="right" width="200px">
      <template v-slot="row">
        <a class="btn blue" @click.stop="onCreateOrEdit(row)"
          >{{ Kooboo.text.common.setting }}</a
        >
      </template>
    </kb-table-column>
  </kb-table>
  <div
    class="modal fade"
    data-backdrop="static"
    data-keyboard="false"
    v-kb-modal="showEditModal"
  >
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button class="close" @click="showEditModal=false"
            ><i class="fa fa-close"></i
          ></button>
          <h4 class="modal-title">{{ editModalTitle }}</h4>
        </div>
        <div class="modal-body" v-if="showEditModal&&types">
          <kb-form :model="editModel" :rules="rules" ref="form">
            <kb-form-item prop="name">
              <label class="control-label col-md-3">Name</label>
              <div class="col-md-9">
                <input
                  type="text"
                  class="form-control"
                  v-model="editModel.name"
                  :disabled="!isNew"
                />
              </div>
            </kb-form-item>
            <kb-form-item prop="matcher">
              <label class="control-label col-md-3">Matcher</label>
              <div class="col-md-9">
                <select v-model="editModel.matcher" class="form-control">
                  <option
                    v-for="item in types.matcher"
                    :key="item.name"
                    :value="item.name"
                    >{{ item.display }}</option
                  >
                </select>
                <template v-if="editModel.matcher=='Condition'">
                  <div
                    v-for="(item,index) in editModel.conditions"
                    style="display: flex; margin-top: 5px; align-items: center"
                  >
                    <select v-model="item.left" class="form-control">
                      <option v-for="i in ['url','method']" :key="i" :value="i"
                        >{{ i }}</option
                      >
                    </select>
                    <select
                      v-model="item.operator"
                      class="form-control"
                      style="margin: 0 5px"
                    >
                      <option
                        v-for="i in ['=','!=','contains','notcontains','startwith','notstartwith']"
                        :key="i"
                        :value="i"
                        >{{ i }}</option
                      >
                    </select>
                    <input
                      type="text"
                      class="form-control"
                      v-model="item.right"
                    />
                    <button
                      @click="editModel.conditions.splice(editModel.conditions.indexOf(item),1)"
                      style="height: 22px; margin-left: 5px"
                      class="pull-right btn btn-xs"
                      ><i class="fa fa-minus"></i
                    ></button>
                  </div>
                  <button
                    type="button"
                    class="btn btn-xs blue"
                    style="margin-top: 5px"
                    @click="editModel.conditions.push({left:'url',operator:'=',right:''})"
                  >
                    <i class="fa fa-plus"></i>
                  </button>
                </template>
              </div>
            </kb-form-item>
            <kb-form-item prop="action">
              <label class="control-label col-md-3">Action</label>
              <div class="col-md-9">
                <select v-model="editModel.action" class="form-control">
                  <option
                    v-for="item in types.action"
                    :key="item.name"
                    :value="item.name"
                    >{{ item.display }}</option
                  >
                </select>
              </div>
            </kb-form-item>

            <template v-if="editModel.action=='CustomCode'">
              <kb-form-item prop="customCodeName">
                <label class="control-label col-md-3">Code Name</label>
                <div class="col-md-9">
                  <select
                    v-model="editModel.customCodeName"
                    class="form-control"
                  >
                    <option
                      v-for="item in authenticationCodes"
                      :key="item.name"
                      :value="item.name"
                      >{{ item.name }}</option
                    >
                  </select>
                </div>
              </kb-form-item>
            </template>

            <template v-else>
              <kb-form-item prop="failedAction">
                <label class="control-label col-md-3"
                  >{{Kooboo.text.common.failed+Kooboo.text.site.siteLog.action}}</label
                >
                <div class="col-md-9">
                  <select v-model="editModel.failedAction" class="form-control">
                    <option
                      v-for="item in types.failedAction"
                      :key="item.name"
                      :value="item.name"
                      >{{ item.display }}</option
                    >
                  </select>
                </div>
              </kb-form-item>
              <kb-form-item
                v-if="editModel.failedAction=='ResultCode'"
                prop="httpCode"
              >
                <label class="control-label col-md-3">Http Code</label>
                <div class="col-md-9">
                  <input
                    type="number"
                    class="form-control"
                    v-model="editModel.httpCode"
                  />
                </div>
              </kb-form-item>
              <kb-form-item
                v-if="editModel.failedAction=='Redirect'"
                prop="url"
              >
                <label class="control-label col-md-3">Url</label>
                <div class="col-md-9">
                  <input
                    type="text"
                    class="form-control"
                    v-model="editModel.url"
                  />
                </div>
              </kb-form-item>
            </template>
          </kb-form>
        </div>
        <div class="modal-footer">
          <button @click="onSave" class="btn green">Save</button>
          <button @click="showEditModal=false" class="btn gray">Cancel</button>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
  Kooboo.loadJS([
    "/_Admin/Scripts/components/kbBreadcrumb.js",
    "/_Admin/Scripts/components/kbForm.js",
    "/_Admin/Scripts/components/kbTable.js",
    "/_Admin/Scripts/components/kbRelationModal.js",
    "/_Admin/Scripts/kooboo/Guid.js",
  ]);
  new Vue({
    el: "#app",
    data: function () {
      var me = this;
      return {
        breads: [
          {
            name: "SITES",
          },
          {
            name: "DASHBOARD",
          },
          {
            name: Kooboo.text.common.authentication,
          },
        ],
        model: [],
        types: null,
        selectedRows: [],
        showEditModal: false,
        editModel: null,
        authenticationCodes: [],
      };
    },
    mounted: function () {
      var me = this;
      Kooboo.Authentication.getTypes().then(function (res) {
        if (res.success) {
          me.types = res.model;
        }
      });
      me.getList();
    },
    computed: {
      isNew: function () {
        if (!this.editModel) return true;
        return this.editModel.id == Kooboo.Guid.Empty;
      },
      editModalTitle: function () {
        if (this.isNew) {
          return Kooboo.text.common.create + ": ";
        } else {
          return Kooboo.text.common.edit + ": " + this.editModel.name;
        }
      },
      rules: function () {
        var me = this;
        var rules = {};

        if (me.editModel.action == "CustomCode") {
          rules.customCodeName = [
            {
              required: true,
              message: Kooboo.text.validation.required,
            },
          ];
        }

        if (me.editModel.failedAction == "ResultCode") {
          rules.httpCode = [
            {
              required: true,
              message: Kooboo.text.validation.required,
            },
          ];
        }

        if (me.editModel.failedAction == "Redirect") {
          rules.url = [
            {
              required: true,
              message: Kooboo.text.validation.required,
            },
          ];
        }

        if (me.isNew) {
          rules.name = [
            {
              required: true,
              message: Kooboo.text.validation.required,
            },
            {
              pattern: /^([A-Za-z][\w\-\.]*)*[A-Za-z0-9]$/,
              message: Kooboo.text.validation.objectNameRegex,
            },
            {
              min: 1,
              max: 64,
              message:
                Kooboo.text.validation.minLength +
                1 +
                ", " +
                Kooboo.text.validation.maxLength +
                64,
            },
            {
              remote: {
                url: Kooboo.Authentication.isUniqueName(),
                data: function () {
                  return {
                    name: me.editModel.name,
                  };
                },
              },
              message: Kooboo.text.validation.taken,
            },
          ];
        }

        return rules;
      },
    },
    methods: {
      onDelete: function () {
        var me = this;
        var haveRelations = this.selectedRows.some(function (s) {
          return s.relations && Object.keys(s.relations).length;
        });

        var confirmStr = haveRelations
          ? Kooboo.text.confirm.deleteItemsWithRef
          : Kooboo.text.confirm.deleteItems;

        var ids = this.selectedRows.map(function (m) {
          return m.id;
        });

        if (!confirm(confirmStr)) return;

        Kooboo.Authentication.Deletes({
          ids: ids,
        }).then(function (res) {
          if (res.success) {
            Kooboo.View.getList().then(function (res) {
              me.model = _.sortBy(res.model, [
                function (r) {
                  return r.lastModified;
                },
              ]).reverse();
            });
            window.info.done(Kooboo.text.info.delete.success);
          } else {
            window.info.done(Kooboo.text.info.delete.fail);
          }
        });
      },
      onCreateOrEdit: function (row) {
        if (row) {
          this.editModel = JSON.parse(JSON.stringify(row));
        } else {
          this.editModel = {
            id: Kooboo.Guid.Empty,
            name: "",
            matcher: "None",
            action: "None",
            failedAction: "None",
            customCodeName: "",
            httpCode: 401,
            url: "/",
            conditions: [],
          };
        }
        this.showEditModal = true;
      },
      onSave: function () {
        var me = this;
        if (!me.$refs.form.validate()) return;

        if (me.editModel.matcher == "Condition") {
          if (me.editModel.conditions.length == 0)
            return alert("You need add Conditions!");
          if (
            me.editModel.conditions.filter(function (f) {
              return !f.right;
            }).length > 0
          )
            return alert("Condition value can not be empty!");
        }

        Kooboo.Authentication.post(me.editModel).then(function () {
          me.getList();
          me.showEditModal = false;
        });
      },
      getList: function () {
        var me = this;
        Kooboo.Authentication.getList().then(function (res) {
          if (res.success) {
            me.model = res.model;
            me.selectedRows = [];
          }
        });
      },
      onDelete: function () {
        var me = this;
        if (!confirm(Kooboo.text.confirm.deleteItems)) return;

        var ids = this.selectedRows.map(function (m) {
          return m.id;
        });

        Kooboo.Authentication.Deletes({
          ids: ids,
        }).then(function (res) {
          if (res.success) {
            me.getList();
            window.info.done(Kooboo.text.info.delete.success);
          } else {
            window.info.done(Kooboo.text.info.delete.fail);
          }
        });
      },
      getParameter: function (row) {
        if (row.action == "CustomCode") return row.customCodeName;
        if (row.failedAction == "None") return "";
        if (row.failedAction == "ResultCode") return row.httpCode;
        if (row.failedAction == "Redirect") return row.url;
      },
      getConditionStr(row) {
        if (row.matcher == "Condition") {
          return row.conditions
            .map(function (m) {
              return m.left + " " + m.operator + " '" + m.right + "'";
            })
            .join(" && ");
        } else return "";
      },
    },
    watch: {
      "editModel.action": function (value) {
        var me = this;
        if (value == "ResultCode") this.editModel.httpCode = 401;
        if (value == "Redirect") this.editModel.url = "/";
        if (value == "CustomCode") {
          Kooboo.Code.getListByType({
            codetype: "Authentication",
          }).then(function (res) {
            if (res.success) {
              me.authenticationCodes = res.model;
              if (res.model.length > 0)
                me.editModel.customCodeName = res.model[0].name;
            }
          });
        }
      },
    },
  });
</script>
